import {
    getWeekDate,
    getTime,
    formatDateArray,
    getDate
} from '/js/util.js'
import {
    getStudentByTeacher,
    nobuy,
    buy,
    listenerEntryCourse
} from './teacherDetail.js'
import {
    dialog,
    dialogListener
} from './assess.js'
import {
    dialogOneStep,
    sureButton
} from '../../../../teacher/components/teachers.js'
import loginRTM from './rtmToken.js'
import loading from '/js/loading.js'
let image = [],
    isbuy = false,
    teachers = [], //teacher id
    teacher_information = [], //teachers information
    informationArray = [],
    teacher_detail = {},
    current_teacher_buy = {}, //current the teacher
    list = [],
    user_img = JSON.parse(localStorage.getItem('user')).user_img,
    teacherimg = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201503%2F11%2F20150311215235_Jr5JK.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640227971&t=a1b74a040e7ad560e9eb3f36dd29d57b',
    id = 0,
    left_chat_length = 0,
    clients = null,
    currentList = {},
    teacherid = null,
    user_id = JSON.parse(localStorage.getItem('user')).user_id,
    header = {
        'x-agora-token': localStorage.getItem('rtmToken'),
        'x-agora-uid': JSON.parse(localStorage.getItem('user')).user_id,
    },
    start = getDate(new Date(), 7),
    end = formatDateArray(new Date()),
    start_time = `${start.y}-${start.month}-${start.d}T${start.h}:${start.minute}:${start.s}Z`,
    end_time = `${end.y}-${end.month}-${end.d}T${end.h}:${end.minute}:${end.s}Z`,
    quotientSrc,
    offsetSrc,
    quotientDst,
    offsetDst,
    allSrcCount,
    allDstCount

let createMessageWrap = async () => {
    return new Promise(async (resolve) => {
        teacher_detail = {}
        let wrap = document.createElement('div')
        wrap.className = 'header-third'
        await listenerAgora()
        await getAllHistory()
        if (informationArray.length) {
            let left = createWrapLeft()
            let middle = createWrapMiddle()
            wrap.appendChild(left)
            wrap.appendChild(middle)
            $('.body')[0].appendChild(wrap)
            teacherimg = informationArray[0].teacherimg
            createUserChat(informationArray)
            teacherid = informationArray[0].teacherid
            teacher_detail = await getStudentByTeacher(teacherid, new Date().getDay() === 0 ? 7 : new Date().getDay())
            getData(informationArray)
            bottomUlListener()
            uploadImageListener()
            uploadContentListener()
            if (teacher_detail.length && teacher_information.length) {
                isbuy = true
                current_teacher_buy = teacher_detail
                let right = createWrapRight(teacher_information[0], current_teacher_buy)
                $('.header-third')[0].appendChild(right)
                $('.teachername')[0].innerHTML = teacher_information[0].name + '（老师）'
            } else if (teacher_information.length) {
                let right = createWrapRight(teacher_information[0])
                $('.header-third')[0].appendChild(right)
                $('.teachername')[0].innerHTML = teacher_information[0].name + '（老师）'
            }
        } else {
            createWrapNoMessage()
        }
        if (isbuy) {
            //监听事件
            dialog(teacher_information[0])
            starListener()
            dialogListener(teacher_information[0])
            orderClassListener()
            listenerEntryCourse()
        } else {
            orderClassListener()
        }
        setTimeout(() => {
            $('.header-third')[0].style.opacity = 1
            resolve('ok')
        })
    })
}

// get user all message history
let getAllHistory = async () => {
    informationArray = [], teachers = []

    //发送方
    let source = await selectSrcMessageHistory(0, user_id, '', 'desc')
    //去重
    source = duplicateRemoval(source, 'dst')

    //接收方
    let destination = await selectDstMessageHistory(0, '', user_id, 'desc')
    //去重
    destination = duplicateRemoval(destination, 'src')


    informationArray = informationArray.concat(source, destination)
    informationArray = informationArray.sort((a, b) => {
        return b.ms - a.ms
    })
    //去重
    for (let i = 0; i < informationArray.length; i++) {
        for (let j = i + 1; j < informationArray.length; j++) {
            if ((informationArray[i].src === informationArray[j].dst) && (informationArray[i].dst === informationArray[j].src)) {
                informationArray.splice(j, 1)
            }
        }
    }
    informationArray.forEach(item => {
        if (item.dst !== user_id && !isNaN(parseInt(item.dst))) {
            teachers.push(parseInt(item.dst))
        }
        if (item.src !== user_id && !isNaN(parseInt(item.src))) {
            teachers.push(parseInt(item.src))
        }
    })

    let res = await ajax('ergodic_query', {
        listid: teachers
    }, 'post')

    if (res?.data) {
        teacher_information = res.data.filter(item => {
            return item !== null
        })
        //循环更新图像
        teacher_information.forEach((item, index) => {
            informationArray[index].teacherimg = item.teacherimg
            informationArray[index].teachername = item.name + '（老师）'
        })
    }




}

// listen agora channel or user one point one message
let listenerAgora = async () => {
    let {
        client
    } = await loginRTM()

    //显示对端发送的消息
    client.on('MessageFromPeer', function (message, peerId, r) {
        let item = {
            content: message.text,
            createTime: getTime(new Date()),
            id: user_id,
            src : peerId,
            teacherimg,
            uid: peerId
        }
        // createContent(item, id)
        if (peerId === teacherid) {
            createContent(item, id)
        }

        let isinList = false
        list.forEach(item => {
            if (item.dst === peerId || item.src === peerId) {
                isinList = true
            }
        })
        if (!isinList) {
            domAdd(message, peerId, r)
        } else {
            domUpdate(message, peerId, r)
        }

    })

    clients = client
}

let domUpdate = (message, peerId, r) => {
    $('.bottom-ul-list').each(function (index) {
        let {
            teacher
        } = $(this)[0].dataset
        teacher = JSON.parse(teacher)
        if (teacher.teacherid === peerId) {
            this.children[1].children[1].innerHTML = message.text.includes('img') ? `<div>图片</div>` : message.text
            this.children[1].children[0].children[1].innerText = getWeekDate(r.serverReceivedTs)
        }
    })
}

let domAdd = (message, peerId, r) => {
    left_chat_length = list.length
    list.push({
        content: "6666",
        day: getWeekDate(r.serverReceivedTs),
        dst: user_id,
        message_type: "peer_message",
        ms: r.serverReceivedTs,
        payload: "6666",
        sendtype: "destination",
        src: peerId,
        teacherid: peerId,
        teacherimg: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201503%2F11%2F20150311215235_Jr5JK.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640227971&t=a1b74a040e7ad560e9eb3f36dd29d57b",
        teachername: `${peerId}（老师）`
    })
    let frag = document.createDocumentFragment()
    let teacher = {
        teacherid: peerId,
        teachername: peerId + '（老师）',
    }
    teacher = JSON.stringify(teacher)

    let li = document.createElement('li')
    li.setAttribute('data-index', left_chat_length)
    li.setAttribute('sendtype', 'destination')
    li.className = `bottom-ul-list ${left_chat_length === 0 ? 'chat-active' : ''}`
    li.dataset.teacher = teacher

    let img = `<img data-sendtype='destination' data-teacher=${teacher} data-index="${left_chat_length}" width="48" height="48" style="border-radius: 50%;" src="${user_img}"/>`
    let list_detail = `<div class="list-detail" data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}">
        <div data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}" style="width: 90%;display: flex;align-items: center;justify-content: space-between;">
            <span style="color: #3C3C3C;" data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}">${peerId + '（老师）'}</span>
            <span style="color: #3C3C3C;" data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}">${getWeekDate(r.serverReceivedTs)}</span>
        </div>
        <div data-teacher=${teacher} data-sendtype='destination'  data-index="${left_chat_length}" class='aside-teacher-content'>${message.text}</div>
    </div>`
    li.innerHTML = img + list_detail
    frag.appendChild(li)
    $('.bottom-ul')[0].appendChild(frag)
}

//select src message history
let selectSrcMessageHistory = async (offsetSrc, source, destination, order = 'asc') => {
    let res = await $.ajax({
        url: 'https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query',
        data: JSON.stringify({
            filter: {
                source,
                destination,
                start_time,
                end_time
            },
            limit: 100,
            offset: offsetSrc,
            order,
        }),
        headers: header,
        async: true, //异步或同步，默认异步
        dataType: 'json', //服务器返回类型 
        type: 'post'
    }).then(async res => {
        let {
            location
        } = res
        location = location.split('/')[5]
        let list = await $.ajax({
            url: `https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query/${location}`,
            type: 'get',
            headers: header,
            dataType: 'json',
            async: true
        })
        list.messages = list.messages.filter(item => {
            return item.message_type !== 'group_message'
        })
        list.messages.forEach(item => {
            item.teacherid = item.dst
            item.teacherimg = teacherimg
            item.user_img = user_img
            item.teachername = item.dst + '（老师）'
            item.content = item.payload.includes('img') ? `<div>图片</div>` : item.payload
            item.sendtype = 'source'
            item.day = getWeekDate(item.ms)
            item.createTime = getTime(item.ms)
        })
        return list.messages
    }).catch(err => {
        console.log(err)
    })
    return res
}

// 去重
let duplicateRemoval = (message, key) => {
    let obj = {}

    function deWeightFour() {
        message = message.reduce(function (a, b) {
            obj[b[key]] ? '' : obj[b[key]] = true && a.push(b);
            return a;
        }, [])
        return message;
    }
    let newArr = deWeightFour()
    return newArr
}

// select dst message history
let selectDstMessageHistory = async (offsetDst, source, destination, order = 'asc') => {
    let res = await $.ajax({
        url: 'https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query',
        data: JSON.stringify({
            filter: {
                source,
                destination,
                start_time,
                end_time
            },
            limit: 100,
            offset: offsetDst,
            order,
        }),
        headers: header,
        async: true, //异步或同步，默认异步
        dataType: 'json', //服务器返回类型 
        type: 'post'
    }).then(async res => {
        let {
            location
        } = res
        location = location.split('/')[5]
        let list = await $.ajax({
            url: `https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query/${location}`,
            type: 'get',
            headers: header,
            dataType: 'json',
            async: true
        })
        list.messages = list.messages.filter(item => {
            return item.message_type !== 'group_message'
        })
        list.messages.forEach(item => {
            item.teacherid = item.src
            item.teacherimg = teacherimg
            item.user_img = user_img
            item.teachername = item.src + '（老师）'
            item.content = item.payload.includes('img') ? `<div>图片</div>` : item.payload
            item.sendtype = 'destination'
            item.day = getWeekDate(item.ms)
            item.createTime = getTime(item.ms)
        })
        return list.messages
    }).catch(err => {
        console.log(err)
    })
    return res
}

let createContent = (item, id) => {
    let frag2 = document.createDocumentFragment()
    createUserChatDetail(frag2, item, id++)
    $('.middle-center')[0].children[0].appendChild(frag2)
    requestAnimationFrame(() => {
        let length = $('.middle-center')[0].children[0].children.length - 1,
            height = 0
        let scrollHeight = $('.middle-center')[0].children[0].children[length].scrollHeight
        if (image.length) {
            height = image.length * 161
        }
        if (item.content) {
            height += scrollHeight - 10 + 10
        }
        $('.middle-center')[0].scrollTop = $('.middle-center')[0].scrollHeight
        $('.bottom-input')[0].innerHTML = '请输入您的信息'
    })
}

let createUserChat = (data) => {
    list = data
    let frag = document.createDocumentFragment()
    for (let i = 0; i < data.length; i++) {
        let teacher = {
            teacherid: data[i].teacherid,
            teachername: data[i].teachername,
        }
        teacher = JSON.stringify(teacher)

        let li = document.createElement('li')
        li.setAttribute('data-index', i)
        li.setAttribute('sendtype', data[i].sendtype)
        li.className = `bottom-ul-list ${i === 0 ? 'chat-active' : ''} animated slideInDown`
        li.dataset.teacher = teacher

        let img = `<img data-sendtype=${data[i].sendtype} data-teacher=${teacher} data-index="${i}" width="48" height="48" style="border-radius: 50%;" src="${data[i].teacherimg}"/>`
        let list_detail = `<div class="list-detail" data-sendtype=${data[i].sendtype}  data-teacher=${teacher} data-index="${i}">
            <div data-sendtype=${data[i].sendtype}  data-teacher=${teacher} data-index="${i}" style="width: 90%;display: flex;align-items: center;justify-content: space-between;">
                <span style="color: #3C3C3C;" data-sendtype=${data[i].sendtype}  data-teacher=${teacher} data-index="${i}">${data[i].teachername}</span>
                <span style="color: #3C3C3C;" data-sendtype=${data[i].sendtype}  data-teacher=${teacher} data-index="${i}">${data[i].day}</span>
            </div>
            <div data-teacher=${teacher} data-sendtype=${data[i].sendtype}  data-index="${i}" class='aside-teacher-content'>${data[i].content ? data[i].content : '尚没有信息'}</div>
        </div>`
        li.innerHTML = img + list_detail
        frag.appendChild(li)
    }
    $('.bottom-ul')[0].appendChild(frag)
}

let getData = async () => {
    let r = [],
        r1 = [],
        r2 = []

    //先去查询最近所有的消息记录 当作这次信息的偏移量 去查找最近的消息记录
    let recentlyChatSource = await $.ajax({
        url: 'https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/count',
        headers: header,
        async: true, //异步或同步，默认异步
        dataType: 'json', //服务器返回类型 
        data: {
            source: user_id,
            destination: teacherid,
            start_time,
            end_time
        },
        type: 'get'
    }).then(async res => {
        return res.count
    })

    let recentlyChatDst = await $.ajax({
        url: 'https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/count',
        headers: header,
        async: true, //异步或同步，默认异步
        dataType: 'json', //服务器返回类型 
        data: {
            source: teacherid,
            destination: user_id,
            start_time,
            end_time
        },
        type: 'get'
    }).then(async res => {
        return res.count
    })

    allSrcCount = recentlyChatSource
    allDstCount = recentlyChatDst
    if (recentlyChatSource > 100) {

        quotientSrc = parseInt(recentlyChatSource / 100)
        offsetSrc = recentlyChatSource - (quotientSrc * 100)
    } else {
        offsetSrc = 0
    }
    if (recentlyChatDst > 100) {
        quotientDst = parseInt(recentlyChatDst / 100)
        offsetDst = recentlyChatDst - (quotientDst * 100)
    } else {
        offsetDst = 0
    }


    r1 = await selectSrcMessageHistory(offsetSrc, user_id, teacherid)
    r2 = await selectDstMessageHistory(offsetDst, teacherid, user_id)
    r = r.concat(r1, r2)
    r = r.sort((a, b) => {
        return a.ms - b.ms
    })
    initUserChatDetail(r)
}

let bottomUlListener = () => {
    let user = localStorage.getItem('user')
    user = JSON.parse(user)

    $('.bottom-ul')[0].addEventListener('click', async (e) => {
        if (e.target.nodeName.toLowerCase() !== 'ul') {
            loading.showLoading({
                type: 2,
                tip: "loading..."
            })
            $('.middle-center')[0].children[0].innerHTML = ''
            let index1 = 0;
            if ($(e.target)[0].dataset?.teacher) {
                let {
                    teacher,
                    index,
                    sendtype
                } = $(e.target)[0].dataset
                index1 = index
                currentList = list[index]
                teacherimg = currentList.teacherimg
                teacher = JSON.parse(teacher)
                teacherid = teacher.teacherid
                Array.from($('.bottom-ul')[0].children).forEach((item, i) => {
                    if (i == index) {
                        item.className = 'bottom-ul-list chat-active'
                    } else {
                        item.className = 'bottom-ul-list '
                    }
                })
                $('.teachername')[0].innerHTML = teacher.teachername
                getData()
            } else {
                let {
                    teacher,
                    index,
                    sendtype
                } = $(e.target)[0].parentElement.dataset
                index1 = index
                currentList = list[index]
                teacherimg = currentList.teacherimg
                teacher = JSON.parse(teacher)
                teacherid = teacher.teacherid
                Array.from($('.bottom-ul')[0].children).forEach((item, i) => {
                    if (i == index) {
                        item.className = 'bottom-ul-list chat-active'
                    } else {
                        item.className = 'bottom-ul-list '
                    }
                })
                $('.teachername')[0].innerHTML = teacher.teachername
                getData()
            }
            //动态添加最右边侧边栏的信息
            let day = new Date().getDay()
            if (day === 0) day = 7
            let teacher_detail = await getStudentByTeacher(teacherid, day + '')
            if (teacher_detail.length) {
                isbuy = true
                current_teacher_buy = teacher_detail
                $('.header-third')[0].appendChild(createWrapRight(teacher_information[parseInt(index1)], current_teacher_buy))
                listenerEntryCourse()
                dialog(teacher_information[parseInt(index1)])
                starListener()

                dialogListener(teacher_information[parseInt(index1)])
                orderClassListener()
            } else {
                isbuy = false
                $('.header-third')[0].appendChild(createWrapRight(teacher_information[parseInt(index1)]))
                orderClassListener()
            }

            loading.hideLoading();
        }
    })
}

let uploadImageListener = () => {
    let upload = $('.upload')[0]
    upload.addEventListener('click', (e) => {
        let input = document.createElement('input')
        input.className = 'input'
        input.type = 'file'
        input.accept = 'image/*'
        input.addEventListener('change', async (e) => {
            if (e.target.files[0]) {
                let {
                    url
                } = await unploadimg(e.target.files[0],1024 * 1024 * 1024)
                let options = {
                    enableHistoricalMessaging: true,
                    enableOfflineMessaging: true
                }
                let res = await clients.sendMessageToPeer({
                    text: `<img src='${url}' width='100' height='100' />`
                },
                    teacherid,
                    options
                )
                if (res) {
                    let item = {
                        content: `<img src='${url}' width='100' height='100' />`,
                        createTime: getTime(new Date()),
                        id: user_id,
                        user_img,
                        src: user_id
                    }
                    let frag2 = document.createDocumentFragment()
                    createUserChatDetail(frag2, item, id++)
                    $('.middle-center')[0].children[0].appendChild(frag2)
                    requestAnimationFrame(() => {
                        let length = $('.middle-center')[0].children[0].children.length - 1,
                            height = 0
                        let scrollHeight = $('.middle-center')[0].children[0].children[length].scrollHeight
                        if (image.length) {
                            height = image.length * 161
                        }
                        if (item.content) {
                            height += scrollHeight - 10 + 10
                        }
                        $('.middle-center')[0].scrollTop = $('.middle-center')[0].scrollHeight
                        $('.bottom-input')[0].innerHTML = '请输入您的信息'
                    })
                    domUpdate({
                        text: `<div>图片</div>`,
                    }, teacherid, {
                        serverReceivedTs: new Date()
                    })
                }
                // gen_base64($('.input')[0].files[0])
                input.remove()
            }else{
                input.remove()
            }
        })
        input.click()
    })
}

//监听scroll滚动
let scrollMessageListener = () => {
    $('.middle-center')[0].addEventListener('scroll', async (e) => {
        if (e.target.scrollTop === 0) {
            if (offsetSrc > 0) {
                if (offsetSrc > 100) {
                    offsetSrc -= 100
                }
                loading.showLoading({
                    type: 1,
                    tip: "loading..."
                })
                let res = await selectSrcMessageHistory(offsetSrc > 100 ? offsetSrc : 0, user_id, teacherid)
                if (offsetSrc < 100) {
                    res = res.splice(0, offsetSrc)
                    offsetSrc = 0
                }
                let frag = document.createDocumentFragment()
                res.forEach(item => {
                    createUserChatDetail(frag, item)
                })
                $('.chat-other')[0] && $('.chat-other')[0].before(frag)
                loading.hideLoading();
            }
            if (offsetDst > 0) {
                if (offsetDst > 100) {
                    offsetDst -= 100
                }
                loading.showLoading({
                    type: 1,
                    tip: "loading..."
                })
                let res = await selectDstMessageHistory(offsetSrc > 100 ? offsetDst : 0, teacherid, user_id)
                if (offsetDst < 100) {
                    res = res.splice(0, offsetDst)
                    offsetDst = 0
                }
                let frag = document.createDocumentFragment()
                res.forEach(item => {
                    createUserChatDetail(frag, item)
                })
                $('.chat-other')[0] && $('.chat-other')[0].before(frag)
                loading.hideLoading();
            }
        }
    })
}

let initUserChatDetail = (data) => {
    let frag = document.createDocumentFragment()
    for (let i = 0; i < data.length; i++) {
        createUserChatDetail(frag, data[i], i)
    }
    $('.middle-center')[0].children[0].appendChild(frag)
    requestAnimationFrame(() => {
        $('.middle-center')[0].scrollTop = $('.middle-center')[0].scrollHeight
    })
    scrollMessageListener()
}

let createUserChatDetail = (frag, item, i) => {
    let li = document.createElement('li')
    li.className = `${item.src == user_id ? 'chat-me' : 'chat-other'}`
    let img = `<img width="30" height="30" style="border-radius: 50%;" src="${item.src === user_id ? item.user_img : item.teacherimg}" alt=""/>`
    let wrap = `<div class="chat-wrap">
        <div class="chat-content">${item.payload ? item.payload : item.content}</div>	
        <div class="chat-time">${item.createTime}</div>	
    </div>`
    li.innerHTML = img + wrap
    frag.appendChild(li)
}

let uploadContentListener = async () => {
    $('.icon-fasong')[0].addEventListener('click', async () => {
        if (!$('.bottom-input')[0].innerText && Array.from($('.bottom-input')[0].children).length === 0) {
            Dreamer.warning('请输入内容')
            return
        }
        let content = document.createElement('div')
        Array.from($('.bottom-input')[0].childNodes).filter((item) => {
            return !item.src
        }).forEach(item => {
            content.appendChild(item)
        })
        if (content) {
            let options = {
                enableHistoricalMessaging: true,
                enableOfflineMessaging: true
            }
            let res = await clients.sendMessageToPeer({
                text: content.innerHTML
            },
                teacherid,
                options
            )
            if (res) {
                let item = {
                    content: content.innerHTML,
                    createTime: getTime(new Date()),
                    id: user_id,
                    user_img,
                    src: user_id
                }
                let frag2 = document.createDocumentFragment()
                createUserChatDetail(frag2, item, id++)
                $('.middle-center')[0].children[0].appendChild(frag2)
                requestAnimationFrame(() => {
                    let length = $('.middle-center')[0].children[0].children.length - 1,
                        height = 0
                    let scrollHeight = $('.middle-center')[0].children[0].children[length].scrollHeight
                    if (image.length) {
                        height = image.length * 161
                    }
                    if (item.content) {
                        height += scrollHeight - 10 + 10
                    }
                    $('.middle-center')[0].scrollTop = $('.middle-center')[0].scrollHeight
                    $('.bottom-input')[0].innerHTML = '请输入您的信息'
                    domUpdate({
                        text: content.innerText,
                    }, teacherid, {
                        serverReceivedTs: new Date()
                    })
                })
            }
        }
    })
}

let createWrapLeft = () => {
    let left = document.createElement('div')
    left.className = 'third-left'
    let top = `
        <div class="left-top" style="height: 36px;margin-left: 6%;">
            <ul class="third-ul animated slideInDown">
                <li class="third-li third-active" onclick="headerClick('third_ul','third-li','third-active',0)">全部
                </li>
            </ul>
        </div>
    `
    let bottom = `
        <div class="left-bottom">
            <ul class="bottom-ul" style="height:100vh;overflow-x: hidden;overflow-y:auto">
            </ul>
        </div>
    `
    left.innerHTML = top + bottom
    return left
}

let createWrapMiddle = () => {
    let middle = document.createElement('div')
    middle.className = 'third-middle'
    middle.style.cssText = 'flex: 1;height: 100%;'
    let top = `
        <div class="middle-top">
            <div></div>
            <div class='teachername' style="margin: auto;font-size: 12px;color: #3C3C3C;"></div>
            <div style="position: absolute;right: 19px;display: flex;align-items: center;">
                <i style="margin-right: 7px;" class="iconfont icon-gantanhao"></i>
                <span style="color: #818181;">你收到骚扰信息可以举报</span>
            </div>
        </div>
    `
    let center = `
        <div class="middle-center">
            <ul>
            </ul>
        </div>
    `
    let bottom = `
        <div class="middle-bottom">
            <div
                style="display: flex;align-items: center;height: 100%;padding-top: 20px;justify-content: space-between; align-items: self-start;max-width: 100%;">
                <div type="input" class="bottom-input" tabindex="-1" contenteditable="true"
                    style="border: none;margin-left: 28px;color: #828282;">
                    <div >请输入您的信息</div>
                </div>
                <div style="display: flex;align-items: center;position:absolute;right:0">
                    <i class="iconfont icon-tupian upload"
                        style="cursor:pointer;font-size: 22px;color: #898989;margin-right: 17px;">
                    </i>
                    <i class="iconfont icon-fasong"
                        style="cursor:pointer;font-size: 22px;color: #4580FE;margin-right: 26px;"></i>
                </div>
            </div>
        </div>
    `
    middle.innerHTML = top + center + bottom
    return middle
}

let createWrapRight = (list, list2) => {
    $('.third-right')[0] && $('.third-right')[0].remove()
    let right = document.createElement('div')
    right.className = 'third-right animated fadeInDown'
    right.style.cssText = 'width: 21%;height: 100%;min-width: 21%;position: relative;'
    let top = `
        <div class="third-top-wrap">
            <img width="39" height="38" src="${list.teacherimg}" alt="">
            <div>${list.name + '（老师）'}</div>
            <div>$${list.price}</div>
        </div>
    `
    //头部
    let star_top = document.createElement('div')
    star_top.style.cssText = 'width: 39px'
    //中间
    let star_middle = document.createElement('div')
    star_middle.style.cssText = 'display: flex;align-items: center;'
    for (let i = 0; i < list.star; i++) {
        let i = document.createElement('i')
        i.className = 'iconfont icon-B-pingfen'
        i.style.cssText = 'color:#FDC425'
        star_middle.appendChild(i)
    }
    //尾部
    let star_footer = document.createElement('div')
    star_footer.style.cssText = 'font-size: 12px;color: #8E8E8E;'
    star_footer.innerText = '每小时'
    let star_wrap = document.createElement('div')
    star_wrap.className = 'third-top-wrap'
    star_wrap.style.cssText = 'padding-top:10px'
    star_wrap.appendChild(star_top)
    star_wrap.appendChild(star_middle)
    star_wrap.appendChild(star_footer)
    right.innerHTML = top
    right.appendChild(star_wrap)
    right.appendChild(isbuy ? buy(list, list2) : nobuy())
    return right
}

let createWrapNoMessage = () => {
    let message = `
        <div class='no-message animated fadeIn'>没有聊天的对象 请去首页选择一个（老师）聊天吧</div>
    `
    $('.header-third')[0].innerHTML = message
}

let starListener = () => {
    $('.dialog-open-star')[0].addEventListener('click', (e) => {
        $('.message-dialog1').show()
    })
}

let orderClassListener = () => {
    $('.order-class')[0].addEventListener('click', async (e) => {
        let timestamp = [],
            time = []
        let res = await ajax("teaching_period_query", {
            "userid": teacherid
        }, "post")
        res.data.forEach(item => {
            if (item.cuyear === new Date().getFullYear() && item.cumonth === new Date().getMonth() + 1) {
                let coursetime = item.coursetime - (new Date().getDay() === 0 ? 7 : new Date().getDay())
                if (coursetime >= 0) {
                    if (coursetime === 0) {
                        let year = new Date().getFullYear()
                        let month = new Date().getMonth() + 1
                        let date = new Date().getDate()
                        let hour = item.timequantum
                        let day = new Date(year + '-' + month + '-' + date + ' ' + hour).getDay()
                        if (day === 0) { day = 6 }
                        if (new Date(year + '-' + month + '-' + date + ' ' + hour).getTime() > new Date().getTime()) {
                            time.push(day - 1)
                            timestamp.push(new Date(year + '-' + month + '-' + date + ' ' + hour).getTime())
                        }
                    } else {
                        let dates = new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * coursetime))
                        time.push(dates.getDay() === 0 ? 6 : dates.getDay() - 1)
                        let newDate = dates.getFullYear() + '-' + parseInt(dates.getMonth() + 1) + '-' + dates.getDate() + '  ' + item.timequantum
                        timestamp.push(new Date(newDate).getTime())
                    }
                }
            }
        })
        timestamp.sort((a, b) => {
            return a - b
        })
        window.timestamp = timestamp
        currentList.id = teacherid
        dialogOneStep(currentList)
        sureButton()
    })
}


export {
    createMessageWrap,
}